package com.shyfu.dao;

import com.shyfu.entities.User;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by Svitlana on 04-Apr-14.
 */
@Repository
public class UserDAOImpl implements UserDAO {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public void addUser(User user) {
        sessionFactory.getCurrentSession().save(user);
    }

    @Override
    public void removeUser(User user) {
        sessionFactory.getCurrentSession().delete(user);
    }

    @Override
    public void removeUser(long id) {
        User user = getUser(id);
        if (user != null) {
            removeUser(user);
        }
    }

    @Override
    public User getUser(String username) {
        List<User> users = sessionFactory.getCurrentSession().createQuery("from User where username = '" + username + "'").list();
        if (users != null) {
            System.out.println("userDaoImpl user = " + users.size());
            return users.get(0);
        }
        return null;
    }

    @Override
    public List<User> getAllUsers() {
        return sessionFactory.getCurrentSession().createQuery("from User order by firstName,lastName").list();
    }

    @Override
    public User getUser(long id) {
        return (User) sessionFactory.getCurrentSession().load(User.class, id);
    }

    @Override
    public void updateUser(User user) {
        sessionFactory.getCurrentSession().update(user);
    }

}
